/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.java2d;

import java.awt.AWTException;
import java.awt.BufferCapabilities;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.ImageCapabilities;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;

import javax.swing.JFrame;

/**
 * Screen used to display output in full screen mode.
 */
public class FullScreen extends Screen{

	/** Window used for fullscreen mode. */
	private JFrame frame;

	/** Used to switch into fullscreen mode. */
	private GraphicsDevice gfxDevice;

	/** Handles double buffering/page flipping. */
	private BufferStrategy bufferStrategy = null;
        
	/** Used to hide mouse cursor. */
	private static final Cursor INVISIBLE_CURSOR = createInvisibleCursor();
    
    /** Default mouse cursor. */
	private static final Cursor DEFAULT_CURSOR = new Cursor(Cursor.DEFAULT_CURSOR);

	private boolean useBlitting = false;
	
	/**
	 * Creates a new FullScreen instance on primary graphics device.
	 *  
	 * @param screenSize  Dimension defining height and width of this screen.
	 * @return {@code Fullscreen} with specified screen dimensions.
	 */
	public static FullScreen openScreen(Dimension size) {
		return openScreen(size.width, size.height);
	}

	/**
	 * Creates a new FullScreen instance on primary graphics device.
	 *  
	 * @param width   screen width in pixel.
	 * @param height  screen height in pixel.
	 * @return {@code Fullscreen} with specified screen dimensions.
	 */
	
	public static FullScreen openScreen(int width, int height) {
		GraphicsDevice device = defaultGraphicsDevice();
		DisplayMode mode = device.getDisplayMode();
	
		mode = new DisplayMode(width, height, mode.getBitDepth(), mode.getRefreshRate());
	
		return new FullScreen(mode, device);
	}
	
	/**
	 * Createa a new FullScreen instance on primary graphics device.
	 * 
	 * @return {@code Fullscreen} with default screen dimensions.
	 */
	public static FullScreen openScreen() {
		GraphicsDevice device = defaultGraphicsDevice();
		return new FullScreen(device.getDisplayMode(), device);		
	}
    
	/**
	 * Creates a new FullScreen instance on secondary graphics device.
	 * 
	 * @param screenSize  Dimension object defining height and width 
	 *                    of this screen.
	 */
	public static FullScreen openSecondaryScreen(Dimension size) {
		GraphicsDevice device = secondaryGraphicsDevice();
		DisplayMode mode = device.getDisplayMode();
        
		mode = new DisplayMode(size.width, size.height, 
				mode.getBitDepth(), mode.getRefreshRate());
        
		return new FullScreen(mode, device);
    }
    

    /**
     * Creates a new FullScreen instance on specified graphics device.
     * 
     * @param mode    DisplayMode specified resolution and color depth
     * @param device  GraphicsDevice used to open screen
     */
    private FullScreen(DisplayMode mode, GraphicsDevice device) {
    	super(mode.getWidth(), mode.getHeight());
    	gfxDevice = device;
    	frame = createFrame();
	
    	gfxDevice.setFullScreenWindow(frame);
    	try {
    		gfxDevice.setDisplayMode(mode);
    	} catch (IllegalArgumentException e) {
        	gfxDevice.setFullScreenWindow(null);
        	throw(e);
        }
	
    	
    	bufferStrategy = createBufferStrategy(frame);	
    }
    
    /**
     * Hides the mouse cursor.
     */
    public void hideMouseCursor() {
    	frame.setCursor(INVISIBLE_CURSOR);
    }
    
    /**
     * Displays the standard mouse cursor.
     */
    public void showMouseCursor() {
    	frame.setCursor(DEFAULT_CURSOR);
    }    
    
    /**
     * Creates JFrame object to be used as full screen window.
     * 
     * @return JFrame to be used as full screen window.
     */
    private JFrame createFrame() {
    	JFrame frame = new JFrame();
    	frame.setUndecorated(true);
    	frame.setResizable(false);
    	frame.setIgnoreRepaint(true);	
	
    	return frame;
    }
    
    /**
     * Creates an appropriate BufferStrategy for specified JFrame object.
     * 
     * @param frame JFrame used to create BufferStrategy.
     * @return BufferStrategy used for double buffering or page flipping.
     */
    private BufferStrategy createBufferStrategy(JFrame frame) {
	
    	if (!useBlitting) {
    		frame.createBufferStrategy(2);
    		return frame.getBufferStrategy();
    	}
    	
    	// for unkown reason, in some cases blitting ist faster than page flipping
    	// so just let us disable flipping by specifieng this BufferCapabilities
    	BufferCapabilities ba = 
    		new BufferCapabilities(
    			new ImageCapabilities(true), 
    			new ImageCapabilities(true), 
    			null);
        
		try {
			frame.createBufferStrategy(2, ba);
		} catch (AWTException e) {
			// TODO handle this exception
		    throw new RuntimeException(e);
		}
		
		return frame.getBufferStrategy();
	}

	/** 
	 * Created an invisible cursor used to hide the standard mouse cursor.
	 * 
	 * @return Cursor object that shows nothing.
	 */
    private static Cursor createInvisibleCursor() {
    	return Toolkit.getDefaultToolkit().createCustomCursor(
    			Toolkit.getDefaultToolkit().getImage(""), new Point(0, 0), "invisible");
    }
    
	/**
	 * Returns the secondary graphics device if present.
	 * 
	 * @return secondary graphics device if present, <code>null</code> otherwise
	 */
	private static GraphicsDevice secondaryGraphicsDevice() {
		GraphicsEnvironment ge = GraphicsEnvironment
				.getLocalGraphicsEnvironment();

		GraphicsDevice defaultDevice = ge.getDefaultScreenDevice();
		GraphicsDevice[] devices = ge.getScreenDevices();

		for (int i = 0; i < devices.length; i++) {
			if (devices[i] != defaultDevice) {
				return devices[i];
			}
		}

		return null;
	}
	
	/**
	 * Retrieves default graphics device of local {@code GraphicsEnvironment}.
	 * 
	 * @return GraphicsDevice from the local graphics environment.
	 */
	private static GraphicsDevice defaultGraphicsDevice() {
		GraphicsEnvironment ge = 
			GraphicsEnvironment.getLocalGraphicsEnvironment();

		return ge.getDefaultScreenDevice();
	}
    
	@Override
	public Component getComponent() {
		return frame;
	}

	@Override
	public Graphics2D getGraphicsContext() {
		return (Graphics2D) bufferStrategy.getDrawGraphics();
	}

	@Override
	public void update() {
		if (!bufferStrategy.contentsLost()) {
			bufferStrategy.show();
		}

		// Sync the display on some systems.
		// (on Linux, this fixes event queue problems)
		Toolkit.getDefaultToolkit().sync();
	}

	public void close() {
		frame.dispose();
		gfxDevice.setFullScreenWindow(null);
	}

	@Override
	public void waitUntilReady() {
		// intentionally left empty
	}

	@Override
	public GraphicsConfiguration getGraphicsConfiguration() {
		return this.frame.getGraphicsConfiguration();
	}

	@Override
	public boolean isFullscreen() {
		return true;
	}
}
